package com.qmgyl.marketshop.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.qmfresh.service.entity.AdminUser;
import com.qmfresh.service.shop.facade.dto.LoginBean;
import com.qmgyl.marketshop.api.ServiceApi;
import com.qmgyl.marketshop.vo.OrderStatsResult;
import com.qmgyl.marketshop.vo.ServiceResult;

@Controller
public class HomeController {
	
	@Autowired
	private ServiceApi serviceApi;
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(HttpServletRequest request,ModelMap model){
		String token = (String)request.getSession().getAttribute("token");
		if(StringUtils.isNotBlank(token)) {
			return "redirect:/admin/index";
		}
		
		return "login";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(String username,String password,HttpServletRequest request,Model model){
		LoginBean lb = new LoginBean();
		lb.setUsername(username);
		lb.setPassword(password);
		ServiceResult<AdminUser> sr = serviceApi.login(lb);
		if(sr.getSuccess()) {
			request.getSession().setAttribute("token", sr.getBody().getToken());
			return "redirect:/admin/index";
		}
		else {
			model.addAttribute("error", sr.getMessage());
			return "redirect:/";
		}
		
		
	}
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String login(HttpServletRequest request){
		request.getSession().invalidate();
		return "redirect:/";
	}
	@RequestMapping(value="/{name}", method = RequestMethod.GET)
	public String hello(@PathVariable("name") String name){
		return name;
	}
	
	@RequestMapping(value="/admin/{name}")
	public String admin(@PathVariable("name") String name){
		
		return "admin/" + name;
	}
	
	@RequestMapping(value="/admin/index")
	public String adminIndex(Model model){
		OrderStatsResult osr = serviceApi.realTimeStats();
		DateTime end = DateTime.now();
		DateTime start = end.minusDays(30);
		List<OrderStatsResult> osrs = serviceApi.daysOrderStats(start.toDate(), end.toDate());
		model.addAttribute("stats", osr);
		model.addAttribute("dayStats", osrs);
		
		return "admin/index";
	}
}
